package com.ycsj.goldmedalnewconcept.student.activity;

import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.blankj.utilcode.util.ToastUtils;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.ycsj.common.base.BaseActivity;
import com.ycsj.common.base.BaseApplication;
import com.ycsj.common.base.BusInfo;
import com.ycsj.common.base.SpKeys;
import com.ycsj.common.manager.BqaManager;
import com.ycsj.common.manager.PickerManager;
import com.ycsj.common.manager.SrfManager;
import com.ycsj.common.utils.DateUtils;
import com.ycsj.common.utils.GsonUtil;
import com.ycsj.common.utils.SPUtil;
import com.ycsj.common.utils.UiUtils;
import com.ycsj.goldmedalnewconcept.R;
import com.ycsj.goldmedalnewconcept.common.HttpAddress;
import com.ycsj.goldmedalnewconcept.common.TkKeys;
import com.ycsj.goldmedalnewconcept.common.http.HttpUtils;
import com.ycsj.goldmedalnewconcept.common.util.AccountUtils;
import com.ycsj.goldmedalnewconcept.common.util.LpUtils;
import com.ycsj.goldmedalnewconcept.common.util.StateCodeUtils;
import com.ycsj.goldmedalnewconcept.student.adapter.StHomeWorkRvAdapter;
import com.ycsj.goldmedalnewconcept.student.bean.StHomeWorkInfo;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.Call;


/**
 * 学生端-我的练习
 */
public class MyHomeWorkActivity extends BaseActivity {

    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.lv_edit)
    ImageView lvEdit;
    @BindView(R.id.ll_title)
    LinearLayout llTitle;
    @BindView(R.id.rv)
    RecyclerView rv;
    @BindView(R.id.srf)
    SmartRefreshLayout srf;
    @BindView(R.id.rl_loading)
    RelativeLayout rlLoading;

    //定义上传服务器的时间,格式暂定为yyyy年-MM月
    private String time;

    //列表数据
    private List<StHomeWorkInfo.HomeworkBean> oldDatas;

    //空视图
    private View emptyView;

    //适配器
    private StHomeWorkRvAdapter adapter;


    @Override
    protected int getContentLayout() {
        return R.layout.activity_my_home_work;
    }

    @Override
    protected void setTitle() {
        super.setTitle();

        if ("0".equals(AccountUtils.getRole(this))) {
            tvTitle.setText("我的课堂练习");
        } else {
            tvTitle.setText("课堂练习");
        }

        lvEdit.setVisibility(View.VISIBLE);
        LpUtils.getRelatLp(UiUtils.dp2px(36), UiUtils.dp2px(36 * 3 / 2));
        lvEdit.setImageResource(R.drawable.img_cander);
    }

    @Override
    protected void init() {

        //初始化状态栏
        initStateBar();

        //初始化下拉刷新
        initSrf();

        //设置查询的初始化时间
        initDate();

        //设置列表
        initRv();

        //请求数据
        http(BqaManager.NORML);
    }


    /**
     * 初始化下拉刷新控件
     */
    private void initSrf() {
        SrfManager.setSmartByPullListener(srf, null);
    }

    /**
     * 设置列表
     */
    private void initRv() {
        oldDatas = new ArrayList<>();
        emptyView = View.inflate(this, R.layout.base_rv_common_empty_view, null);
        TextView tvMsg = emptyView.findViewById(R.id.tv_content);
        tvMsg.setText("该月份暂时没有练习");
        adapter = new StHomeWorkRvAdapter(this, R.layout.student_rv_homework, oldDatas);
    }

    /**
     * 设置初始化查询时间
     */
    private void initDate() {
        time = DateUtils.getTime(new Date(), "yyyy-MM");
    }


    /**
     * 请求接口数据
     *
     * @param method
     */
    private void http(final int method) {

        Map<String, String> map = new HashMap<>();
        map.put("type", "4");
        map.put("acc", AccountUtils.getAccount(this));
        map.put("time", time);
        map.put("ttel", AccountUtils.getTeacher(this));
        map.put("role", AccountUtils.getRole(this));
        map.put("platform", "2");
        map.put("apptoken", AccountUtils.getToken(this));

//        LogUtils.iTag("test", HttpAddress.HOMEWORKLIST + "?type=4&acc=" + AccountUtils.getAccount(this)
//                + "&time=" + time + "&role=" + AccountUtils.getRole(this) + "&paltform=2&apptoken=" + AccountUtils.getToken(this));

        HttpUtils.post(HttpAddress.HOMEWORKLIST, map, this, new HttpUtils.CallBack() {
            @Override
            public void onError(Call call, Exception e, int id) {
                if (null != rlLoading) {
                    rlLoading.setVisibility(View.GONE);
                }
                ToastUtils.showShort(BaseApplication.ERROR);
            }

            @Override
            public void onResponse(String response, int id) {

                if (null != rlLoading) {
                    rlLoading.setVisibility(View.GONE);
                }

                if (null != srf) {
                    srf.setVisibility(View.VISIBLE);
                }

                if (!TextUtils.isEmpty(response)) {

                    StHomeWorkInfo info = null;

                    try {
                        info = GsonUtil.jsonToBean(response, StHomeWorkInfo.class);
                    } catch (Exception e) {
                        Log.i("test", "数据解析异常");
                    }
                    if (null != info) {
                        if ("200".equals(info.getState())) {

                            List<StHomeWorkInfo.HomeworkBean> newDatas = info.getHomework();


                            if (null != newDatas && newDatas.size() != 0) {
                                //更新本地保存的学生的班级
                                if (0 != newDatas.get(0).getClassnum()) {
                                    SPUtil.put(MyHomeWorkActivity.this, SpKeys.CLASSNUM, newDatas.get(0).getClassnum() + "");
                                } else if (!TextUtils.isEmpty(newDatas.get(0).getUSER_CLASS())) {
                                    SPUtil.put(MyHomeWorkActivity.this, SpKeys.CLASSNUM, newDatas.get(0).getUSER_CLASS());
                                }

                                //更新学生的老师账号
                                if (!TextUtils.isEmpty(newDatas.get(0).getUSER_ID())) {
                                    SPUtil.put(MyHomeWorkActivity.this, SpKeys.TEACHER, newDatas.get(0).getUSER_ID());
                                } else if (!TextUtils.isEmpty(newDatas.get(0).getTeacher())) {
                                    SPUtil.put(MyHomeWorkActivity.this, SpKeys.TEACHER, newDatas.get(0).getTeacher());
                                }
                            }

                            if (method == BqaManager.NORML) {

                                oldDatas.clear();
                                oldDatas.addAll(newDatas);
                                BqaManager.setRv(emptyView, MyHomeWorkActivity.this, adapter, rv);
                            } else {

                                BqaManager.updateRvBySmf(BqaManager.PULLREFRESH, null, rv, oldDatas, newDatas, adapter);
                            }
                        } else {
                            Log.i("test", "错误,状态码是:" + info.getState());
                            StateCodeUtils.showSateCode(info.getState());
                        }
                    } else {
                        Log.i("test", "返回数据为空");
                    }
                } else {
                    Log.i("test", "返回数据为空");
                }
            }
        });
    }

    /**
     * 页面控件点击事件
     *
     * @param view
     */
    @OnClick({R.id.iv_back, R.id.lv_edit})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                //返回
                finish();
                break;
            case R.id.lv_edit:
                //选择日期
                showDatePick();
                break;
        }
    }

    /**
     * 选择日期的方法
     */
    private void showDatePick() {
        PickerManager.showPickerByYeaerAndMonth(this, new PickerManager.onSelectedListener() {
            @Override
            public void onTimeSelect(Date date, View v) {
                //选中后的回调
                time = DateUtils.getTime(date, "yyyy-MM");
                //显示加载框
                rlLoading.setVisibility(View.VISIBLE);
                srf.setVisibility(View.GONE);
                http(BqaManager.NORML);
            }
        });
    }


    /**
     * 事件处理
     *
     * @param busInfo
     */
    @Override
    public void busEvent(BusInfo busInfo) {
        super.busEvent(busInfo);
        if (null != busInfo && busInfo.tkMsg == TkKeys.SUCC) {
            http(BqaManager.PULLREFRESH);
        }
    }

    /**
     * 释放播放器
     */
    @Override
    protected void onDestroy() {
        adapter.releaseMediaPlayer();
        super.onDestroy();
    }

}
